
package andre.grids.filesystem.client;

import andre.grids.filesystem.common.*;
import andre.grids.guids.*;
import java.io.*;

/**
 *
 * @author andre
 */
public class RemoteFileInputStream extends InputStream {
    private long filePointer;
    private FileOperations fileOperations;
    private IGuid fileGuid;
    
    public RemoteFileInputStream(IGuid remoteFileGuid, FileOperations remoteServer) {
        fileGuid = remoteFileGuid;
        filePointer = 0;
        fileOperations = remoteServer;
    }

    @Override
    public int available() throws IOException {
        return 0;
    }

    @Override
    public void close() throws IOException {
        fileOperations = null;
        fileGuid = null;
        filePointer = -1;
        super.close();
    }

    @Override
    public synchronized void mark(int readlimit) {
        return;
    }

    @Override
    public boolean markSupported() {
        return false;
    }

    @Override
    public int read(byte[] b) throws IOException {
        int vetSize = b.length;
        ReadOperation readOp = fileOperations.read(fileGuid, filePointer, vetSize);
        
        if (readOp.getSize() <= 0)
            return -1;
        
        System.arraycopy(readOp.getData(), 0, b, 0, readOp.getSize());
        filePointer += readOp.getSize();
        return readOp.getSize();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException  {
        ReadOperation readOp = fileOperations.read(fileGuid, filePointer, len);
        
        if (readOp.getSize() <= 0)
            return -1;
        
        System.arraycopy(readOp.getData(), 0, b, off, len);
        filePointer += readOp.getSize();
        return readOp.getSize();
    }

    @Override
    public synchronized void reset() throws IOException {
        filePointer = 0;
    }

    @Override
    public long skip(long n) throws IOException {
        return filePointer += n;
    }

    @Override
    public int read() throws IOException {
        ReadOperation readOp = fileOperations.read(fileGuid, filePointer, 1);
        if (readOp.getSize() <= 0)
            return -1;
        return (int)readOp.getData()[0];
    }
    
}
